import { Injectable } from '@nestjs/common';
import { DbService } from '../../db/db.service';
import PageDto from './dto/page.dto';
import { BuyOrder } from '@app/db/entity/BuyOrder';
import { User } from '@app/db/entity/User';
import { FindOptionsWhere, In } from 'typeorm';

@Injectable()
export class BuyOrderService {
    constructor(
        private readonly db:DbService,
    ){}
    
    async page(dto:PageDto) {
        let result:PaginationResult<BuyOrder & {user?:User}> = {
            total : 0,
            rows : []
        }

        let where:FindOptionsWhere<BuyOrder> = {
            
        }


        
        result.total = await this.db.buyOrder.count(where)

        if(result.total > 0) {
            result.rows = await this.db.buyOrder.pagination(dto.pageNo, dto.pageSize, where, null, {id : 'DESC'})
            const userIds:number[] = []
            const parentIds:number[] = []
            result.rows.forEach(row => {
                if(row.userId > 0 && !userIds.includes(row.userId)) {
                    userIds.push(row.userId)
                }
            })
            
            let users:User[] = []

            if(parentIds.length > 0) {
                users = await this.db.user.find({id: In(userIds)}, {account:true, id:true})
            }
            

            result.rows.forEach(row => {
                

                const user = users.find(v => v.id == row.userId)
                if(user) {
                    row.user = user
                }
                
            })



            
        }



        return result
    }
}
